import React, { Component } from 'react';
import { Form, Input, Button, Row, Col } from 'antd';
import omit from 'omit.js';
import styles from './index.less';
import ItemMap from './map';
import LoginContext from './loginContext';

const FormItem = Form.Item;
const imgs =
    '';
@Form.create()
class WrapFormItem extends Component {
    static defaultProps = {
        getCaptchaButtonText: 'captcha',
        getCaptchaSecondText: 'second'
    };

    constructor(props) {
        super(props);
        this.state = {
            count: 0,
            captchaNum: '',
            isVisible: false
        };
    }

    componentDidMount() {
        const { updateActive, name } = this.props;
        if (updateActive) {
            updateActive(name);
        }
    }

    componentWillReceiveProps(nextProps) {
        const { captchaNum } = this.props;
        // 任何时候props.value.
        if (nextProps.value !== captchaNum) {
            this.setState({
                captchaNum: nextProps.value
            });
        }
    }

    componentWillUnmount() {
        clearInterval(this.interval);
    }

    onGetCaptcha = () => {
        const { onGetCaptcha } = this.props;
        const result = onGetCaptcha ? onGetCaptcha() : null;
        if (result === false) {
            return;
        }
        if (result instanceof Promise) {
            result.then(this.runGetCaptchaCountDown);
        } else {
            this.runGetCaptchaCountDown();
        }
    };

    getFormItemOptions = ({ onChange, defaultValue, customprops, rules, getValueFromEvent }) => {
        const options = {
            rules: rules || customprops.rules,
            getValueFromEvent
        };
        if (onChange) {
            options.onChange = onChange;
        }
        if (defaultValue) {
            options.initialValue = defaultValue;
        }
        return options;
    };

    runGetCaptchaCountDown = () => {
        const { countDown } = this.props;
        let count = countDown || 59;
        this.setState({ count });
        this.interval = setInterval(() => {
            count -= 1;
            this.setState({ count });
            if (count === 0) {
                clearInterval(this.interval);
            }
        }, 1000);
    };

    changeCaptcha = () => {
        const { onClick } = this.props;
        onClick();
    };

    getPasswordStatus = name => {
        // const { isVisible } = this.state;
        const { form } = this.props;
        const value = form.getFieldValue(name);
        const checked = [];
        if (!value) return '';

        if (value.length >= 8 && value.length <= 20) {
            checked.push('step1');
        }
        if (/^(?=.*\d)(?=.*[a-z])(?=.*[A-Z]).*$/.test(value)) {
            checked.push('step2');
        }
        return checked.map(item => styles[item]).join(' ');
    };

    changeVisible = t => {
        const { isVisible } = this.state;
        const checked = [];
        const { value } = t.target;
        if (!value) return '';
        if (value.length >= 8 && value.length <= 20) {
            checked.push('step1');
        }
        if (/^(?=.*\d)(?=.*[a-z])(?=.*[A-Z]).*$/.test(value)) {
            checked.push('step2');
        }
        if (checked.length >= 2) {
            if (isVisible !== false) {
                this.setState({
                    isVisible: false
                });
            }
        } else if (isVisible !== true) {
            this.setState({
                isVisible: true
            });
        }
        return '';
    };

    render() {
        const { count, captchaNum } = this.state;

        const {
            form: { getFieldDecorator }
        } = this.props;

        // 这么写是为了防止restProps中 带入 onChange, defaultValue, rules props
        const {
            onChange,
            customprops,
            defaultValue,
            value,
            rules,
            name,
            getCaptchaButtonText,
            getCaptchaSecondText,
            updateActive,
            type,
            component,
            getValueFromEvent,
            ...restProps
        } = this.props;
        // get getFieldDecorator props
        const options = this.getFormItemOptions(this.props);

        const otherProps = restProps || {};
        if (type === 'Captcha') {
            const inputProps = omit(otherProps, ['onGetCaptcha', 'countDown']);
            return (
                <FormItem>
                    <Row gutter={8}>
                        <Col span={16}>
                            {getFieldDecorator(name, options)(<Input {...customprops} {...inputProps} />)}
                        </Col>
                        <Col span={8}>
                            <Button
                                disabled={count}
                                className={styles.getCaptcha}
                                size="large"
                                onClick={this.onGetCaptcha}
                            >
                                {count ? `${count} ${getCaptchaSecondText}` : getCaptchaButtonText}
                            </Button>
                        </Col>
                    </Row>
                </FormItem>
            );
        }
        if (type === 'ImgCaptcha') {
            const inputProps = omit(otherProps, ['changeCaptcha', 'captchaNum']);
            inputProps.onClick = null; // 清楚掉input框里的onclick事件
            return (
                <FormItem>
                    <Row gutter={12}>
                        <Col span={16}>
                            {getFieldDecorator(name, options)(<Input {...customprops} {...inputProps} />)}
                        </Col>
                        <Col span={8}>
                            <img
                                alt="验证码"
                                src={captchaNum ? `data:image/png;base64,${captchaNum}` : imgs}
                                style={{ width: '90px', height: '40px' }}
                                onClick={this.changeCaptcha}
                            />
                        </Col>
                    </Row>
                </FormItem>
            );
        }
        return (
            <FormItem>
                {getFieldDecorator(
                    name,
                    options
                )(
                    component ? (
                        component({ ...customprops, ...otherProps })
                    ) : (
                        <Input {...customprops} {...otherProps} />
                    )
                )}
            </FormItem>
        );
    }
}

const LoginItem = {};
Object.keys(ItemMap).forEach(key => {
    const item = ItemMap[key];
    LoginItem[key] = props => (
        <LoginContext.Consumer>
            {context => (
                <WrapFormItem
                    customprops={item.props}
                    rules={item.rules}
                    {...props}
                    type={key}
                    updateActive={context.updateActive}
                    form={context.form}
                    component={item.component}
                />
            )}
        </LoginContext.Consumer>
    );
});

export default LoginItem;
